import pygame
import sys
import random
import math
from ecs.world import World
from ecs.systems import RenderSystem, PhysicsSystem, PlayerControlSystem, WeaponSystem, AISystem, StateSystem
from ecs.entity_factory import create_player, create_weapon, create_hamster
from ecs.components import StateTimer, Transform, Renderable, Relation

# 初始化Pygame
pygame.init()  # 初始化所有pygame模块

# 屏幕尺寸
SCREEN_WIDTH = 800  # 屏幕宽度
SCREEN_HEIGHT = 600  # 屏幕高度

# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))  # 创建游戏窗口
pygame.display.set_caption("双人控制 - wsad和方向键")  # 设置窗口标题

# 初始化字体系统
pygame.font.init()  # 初始化字体模块
score_font = pygame.font.SysFont('Arial', 32)  # 创建字体对象，用于显示分数

# 加载mod图标
mod_image = pygame.image.load("assets/mod.png")
mod_rect = mod_image.get_rect()
mod_rect.bottomright = (SCREEN_WIDTH - 10, SCREEN_HEIGHT - 10)

# 是否显示外挂菜单
show_cheat_menu = False

# 创建ECS世界
world = World()

# 注册系统
world.add_system(RenderSystem(screen))
world.add_system(PhysicsSystem())
world.add_system(PlayerControlSystem())
world.add_system(WeaponSystem())
world.add_system(AISystem())
world.add_system(StateSystem())

# 创建玩家实体
player1 = create_player(world, 1, (SCREEN_WIDTH - 100) // 2 - 100, SCREEN_HEIGHT // 2,
                       "assets/吒.png",
                       {'up': pygame.K_w, 'down': pygame.K_s, 'left': pygame.K_a, 'right': pygame.K_d},
                       (SCREEN_WIDTH, SCREEN_HEIGHT))
world.entities.append(player1)

player2 = create_player(world, 2, (SCREEN_WIDTH + 100) // 2 + 100, SCREEN_HEIGHT // 2,
                       "assets/丙.png",
                       {'up': pygame.K_UP, 'down': pygame.K_DOWN, 'left': pygame.K_LEFT, 'right': pygame.K_RIGHT},
                       (SCREEN_WIDTH, SCREEN_HEIGHT))
world.entities.append(player2)

# 设置对手关系 (使用Relation组件)
player1.add_component(Relation(relations={"opponent": player2.id}))
player2.add_component(Relation(relations={"opponent": player1.id}))

# 创建武器实体
weapon = create_weapon(world, player1.id,
                   player1.get_component(Transform).x + player1.get_component(Renderable).sprite.get_width(),
                   player1.get_component(Transform).y + player1.get_component(Renderable).sprite.get_height() // 2,
                   "assets/火尖枪.png")
# 添加武器所有者关系
weapon.add_component(Relation(relations={"owner": player1.id}))
world.entities.append(weapon)

# 创建仓鼠实体
hamster = create_hamster(
    world,
    "assets/仓鼠白芝麻.png",
    (SCREEN_WIDTH, SCREEN_HEIGHT)
)
world.entities.append(hamster)

# 游戏变量
running = True  # 游戏运行状态
clock = pygame.time.Clock()  # 创建时钟对象，用于控制帧率

# 外挂菜单变量
try:
    cheat_font = pygame.font.Font("simhei.ttf", 24)
except:
    cheat_font = pygame.font.SysFont("Microsoft YaHei", 24)
cheat_menu_rect = pygame.Rect(SCREEN_WIDTH - 250, 50, 240, 200)
cheat_menu_color = (50, 50, 50, 200)
cheat_text_color = (255, 255, 255)
cheat_selected = None  # 当前选中的参数
cheat_input = ""  # 用户输入的值

# 获取仓鼠实体组件引用（用于外挂菜单）
hamster_components = {}
for entity in world.entities:
    if entity.has_component("Respawn") and entity.has_component("Combat") and entity.has_component("Health"):
        hamster_components = {
            "respawn": entity.get_component("Respawn"),
            "combat": entity.get_component("Combat"),
            "health": entity.get_component("Health")
        }
        break

def draw_cheat_menu():
    """绘制外挂菜单"""
    # 创建半透明背景
    s = pygame.Surface((cheat_menu_rect.width, cheat_menu_rect.height), pygame.SRCALPHA)
    s.fill(cheat_menu_color)
    screen.blit(s, cheat_menu_rect.topleft)
    
    # 使用系统自带的中文字体
    try:
        chinese_font = pygame.font.Font("simhei.ttf", 24)
    except:
        chinese_font = pygame.font.SysFont("Microsoft YaHei", 24)
    
    # 绘制菜单项
    y = cheat_menu_rect.top + 10
    
    # 仓鼠重生间隔
    respawn_interval = hamster_components.get("respawn", {}).get("interval", 0)
    text = chinese_font.render(f"t.仓鼠重生间隔(秒): {respawn_interval}", True, cheat_text_color)
    screen.blit(text, (cheat_menu_rect.left + 10, y))
    y += 30
    
    # 仓鼠伤害值
    damage_value = hamster_components.get("combat", {}).get("damage", 0)
    text = chinese_font.render(f"y.仓鼠伤害值: {damage_value}", True, cheat_text_color)
    screen.blit(text, (cheat_menu_rect.left + 10, y))
    y += 30
    
    # 仓鼠血量
    health_value = hamster_components.get("health", {}).get("max_health", 0)
    text = chinese_font.render(f"u.仓鼠血量: {health_value}", True, cheat_text_color)
    screen.blit(text, (cheat_menu_rect.left + 10, y))
    y += 30
    
    # 添加操作说明和输入状态
    text = chinese_font.render("输入数字后按回车确认", True, (255, 255, 0))
    screen.blit(text, (cheat_menu_rect.left + 10, y))
    y += 30
    
    # 显示当前输入状态
    if cheat_selected:
        status_text = f"正在修改: {cheat_selected} = {cheat_input}"
        text = chinese_font.render(status_text, True, (0, 255, 255))
        screen.blit(text, (cheat_menu_rect.left + 10, y))

# 血条绘制已迁移到RenderSystem

def draw_background():
    """绘制背景"""
    try:
        background = pygame.image.load("assets/S.png").convert()  # 加载背景图片
        bg_width, bg_height = background.get_size()  # 获取背景图片尺寸
        tiles_x = (SCREEN_WIDTH // bg_width) + 1  # 计算x轴平铺数量
        tiles_y = (SCREEN_HEIGHT // bg_height) + 1  # 计算y轴平铺数量
        for i in range(tiles_x):
            for j in range(tiles_y):
                screen.blit(background, (i * bg_width, j * bg_height))  # 平铺背景
    except Exception as e:
        print(f"背景加载错误: {str(e)}")  # 打印错误信息
        screen.fill((255, 0, 0))  # 使用红色填充背景

# 主游戏循环
while running:
    current_time = pygame.time.get_ticks() / 1000  # 获取当前时间（秒）
    
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # 检测退出事件
            running = False  # 结束游戏循环
        elif event.type == pygame.MOUSEBUTTONDOWN:  # 检测鼠标点击
            if mod_rect.collidepoint(event.pos):  # 点击了mod图标
                show_cheat_menu = not show_cheat_menu  # 切换外挂菜单显示状态
        elif event.type == pygame.KEYDOWN and show_cheat_menu:  # 外挂菜单打开时处理键盘输入
            if event.key == pygame.K_RETURN:  # 回车确认输入
                if cheat_input and cheat_selected:
                    try:
                        value = int(cheat_input)
                        # 更新ECS组件
                        if cheat_selected == "respawn":
                            hamster_components["respawn"]["interval"] = max(1, value)
                        elif cheat_selected == "damage":
                            hamster_components["combat"]["damage"] = max(1, value)
                        elif cheat_selected == "health":
                            hamster_components["health"]["max_health"] = max(1, value)
                            hamster_components["health"]["current_health"] = max(1, value)
                    except ValueError:
                        pass
                    cheat_input = ""
            elif event.key == pygame.K_t:  # 选择重生间隔
                cheat_selected = "respawn"
                cheat_input = str(hamster_components.get("respawn", {}).get("interval", 0))
            elif event.key == pygame.K_y:  # 选择伤害值
                cheat_selected = "damage"
                cheat_input = str(hamster_components.get("combat", {}).get("damage", 0))
            elif event.key == pygame.K_u:  # 选择血量
                cheat_selected = "health"
                cheat_input = str(hamster_components.get("health", {}).get("max_health", 0))
            elif event.key >= pygame.K_0 and event.key <= pygame.K_9:  # 数字输入
                cheat_input += event.unicode
            elif event.key == pygame.K_BACKSPACE:  # 退格删除
                cheat_input = cheat_input[:-1]
            
        # 武器投掷事件（ECS事件）
        elif event.type == pygame.KEYDOWN and not show_cheat_menu:
            if event.key == pygame.K_SPACE:
                # 发送武器投掷事件
                world.events.append({
                    "type": "throw_weapon",
                    "owner_id": player1.id,
                    "target_id": player2.id
                })
            
    # 获取键盘状态
    keys = pygame.key.get_pressed()  # 获取当前按下的键
    
    # 计算时间增量
    dt = clock.get_time() / 1000
    
    # 绘制所有元素
    draw_background()  # 绘制背景
    # 玩家、武器、仓鼠由RenderSystem自动绘制
    
    # 绘制mod图标
    screen.blit(mod_image, mod_rect)
    
    # 绘制外挂菜单
    if show_cheat_menu:
        draw_cheat_menu()
    
    # 血条由RenderSystem自动绘制
    
    # 更新ECS世界（传递时间增量）
    world.update(dt)
    
    # 绘制得分（由StateSystem提供）
    # 获取状态系统实例
    state_system = world.get_system("StateSystem")
    if state_system:
        player1_score = state_system.player1_score
        player2_score = state_system.player2_score
    else:
        player1_score = 0
        player2_score = 0
        
    score_text = score_font.render(f'Zha: {player1_score}  Bing: {player2_score}', True, (255, 255, 255))
    screen.blit(score_text, (10, 10))
    
    # 绘制游戏结束信息（由StateSystem设置）
    game_state = state_system.game_state if state_system else {}
    if game_state.get("game_over"):
        winner = game_state.get("winner", "")
        end_text = score_font.render(f'Game over，{winner} Win!', True, (255, 255, 0))
        text_rect = end_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))
        screen.blit(end_text, text_rect)
    
    pygame.display.flip()  # 更新显示
    clock.tick(60)  # 控制帧率为60FPS

pygame.quit()  # 退出pygame
sys.exit()  # 退出程序